package com.hcbd.tdwt.util;

import static java.lang.Math.floor;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;

import com.hcbd.tdwt.base.Constant;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil  {
    static Pattern pattern = Pattern.compile("[0-9]*");
    /**
     * 读取联系人信息
     *
     * @param uri
     */
    @SuppressLint("Range")
    public static String[] getPhoneContacts(Uri uri, Context context) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            contact[1] = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }
    /**
     * 去掉手机号内除数字外的所有字符
     *
     * @param phoneNum 手机号
     * @return
     */
    public static String formatPhoneNum(String phoneNum) {
        String regex = "(\\+86)|[^0-9]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNum);
        return matcher.replaceAll("");
    }
    /**
     * 手机号验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isMobilePhone(String str) {
       /* Pattern p = null;
        Matcher m = null;
        boolean b = false;
        //验证手机号
        p = Pattern.compile("^[1][3,4,5,6,7,8][0-9]{9}$");
        m = p.matcher(str);
        b = m.matches();
        return b;*/
        if (str.length() != 11) {
            return false;
        } else {
            return true;
        }
    }
    public static boolean isChinese(String str){
        String chinesePattern = "^[\\u4e00-\\u9fa5]+$";
        return str.matches(chinesePattern);
    }
    public static boolean isAlphanumeric(String str) {
        String alphanumericPattern = "^[a-zA-Z0-9]+$";
        return str.matches(alphanumericPattern);
    }
    /**
     * double保留两位小数
     *
     * @param origin
     * @param saveBits
     * @return
     */
    public static double cutTheTail(double origin, int saveBits) {
        BigDecimal b = new BigDecimal(Double.toString(origin));
        return b.setScale(saveBits, BigDecimal.ROUND_DOWN).doubleValue();
    }
    public static boolean isNumeric(String str){
        if(str==null){
            return false;
        }
        Matcher isNum = pattern.matcher(str);
        if(!isNum.matches() ){
            return false;
        }
        return true;
    }
    public static boolean isNumeric(String ...strArray){
        for(String str:strArray){
            if(str==null||"".equals(str)){
                return false;
            }
            Matcher isNum = pattern.matcher(str);
            if(!isNum.matches()){
                return false;
            }
        }
        return true;
    }
    public static String ggaConvertLon(String oldStr,int index){
        String repStr=oldStr.replace(".","");
        return StringUtil.stringInsert(repStr,".",index);
    }
    /**
     * 度分转经纬度
     * 全球经纬度的取值范围为：纬度-90~90，经度-180~180
     * 度分转换： 将度分单位数据转换为度单位数据，公式：度=度+分/60
     * 例如： 经度 = 116°20.12'，纬度 = 39°12.34'
     * 经度 = 116 + 20.12 / 60 = 116.33533°
     * 纬度 = 39 + 12.34 / 60 = 39.20567°
     *
     * @param dm 4005.38389 ddmm.mmmmm
     * @return 40.0897315
     * 11616.02846 dddmm.mmmmm
     * 116.267141
     */
    public static String df2LatLng(String dm) {
        if (dm == null) {
            return "0";
        }
        try {
            dm = dm.replace(" ", "");
            int d = parseInteger(dm.substring(0, dm.lastIndexOf(".") - 2));
            // 兼容经纬度的转换
            double fen = Double.parseDouble(dm.substring(String.valueOf(d).length()));

            double lat = (fen / 60) + Math.abs(d);
            if (lat < 0) {
                lat = -lat;
            }
            return String.format("%.7f", lat);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0";
    }

    public static double analysisLonlat(String value){
        double lonlat = Double.valueOf(value);
        int dd = (int)lonlat / 100;
        int mm = (int)lonlat % 100;
        double ms = lonlat - (int)lonlat;
        return dd+((mm+ms)/60.0);
    }

    // 四舍五入：round - true四舍五入，false直接截取
    public static double roundDouble(double value, int places, boolean round) {
        if (places < 0) {
            throw new IllegalArgumentException("小数位数不能小于0");
        }
        double scale = Math.pow(10, places);
        if(round){return Math.round(value * scale) / scale;}
        else {return Math.floor(value * scale) / scale;}
    }

    public static Integer parseInteger(String str) {
        if (str == null || str.isEmpty()) {
            return 0;
        }
        return Integer.valueOf(str);
    }
    /**
     * dms转经纬度
     * 41951158     14371952
     * 116.5309944  39.9220889
     *
     * @param dms dms 经纬度
     * @return
     */
    public static double dfm2Du(Double dms) {
        int degree = (int) (dms / 360000);
        int minute = (int) ((dms - degree * 360000) / 6000);
        double second = (double) ((dms - degree * 360000 - minute * 6000) / 100.00);
        double digitalDegree = 0.0;
        double num = 60;
        digitalDegree += degree;
        digitalDegree += minute / num;
        digitalDegree += (second / (num * num));

        return Double.parseDouble(String.format("%.7f", digitalDegree));
    }
    /**
     * 保留两位小数，四舍五入的一个老土的方法
     *
     * @param number
     * @return
     */
    public static double formatDouble1(double number) {
        return (double) Math.round(number * 100) / 100;
    }

    /**
     * String转换成double 保留N位小数。
     *
     * @param a
     * @return
     */
    public static double stringToDouble(String a) {
        double b = Double.valueOf(a);
        //此为保留2位小数，若想保留1位小数，则填写#.0  ，以此类推
        DecimalFormat df = new DecimalFormat("#.000000");
        String temp = df.format(b);
        b = Double.valueOf(temp);
        return b;
    }

    /**
     * 在指定位置插入指定字符
     *
     * @param str
     * @param insertStr
     * @param i
     * @return
     */
    public static String stringInsert(String str, String insertStr, int i) {
        //构造一个StringBuilder对象
        StringBuilder sb = new StringBuilder(str);
        sb.insert(i, insertStr);
        return sb.toString();
    }

    /**
     * 从左往右取第一个不为零的数开始取
     *
     * @param str
     * @return
     */
    public static String subStringNotZero(String str) {
        boolean isZero = false;
        StringBuffer strBuffer = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            if (!isZero) {
                if (!str.substring(i, i + 1).equals("0")) {
                    strBuffer.append(str.substring(i, i + 1));
                    isZero = true;
                }
                continue;
            }
            strBuffer.append(str.substring(i, i + 1));
        }
        return strBuffer.toString();
    }

    /**
     * 拼接字符串
     *
     * @param str
     * @param length
     * @return
     */
    public static String appendString(String str, int length) {
        StringBuffer strBuffer = new StringBuffer();
        strBuffer.append(str);
        if (str.length() < length) {
            int complementLength = length - str.length();
            for (int i = 0; i < complementLength; i++) {
                strBuffer.append("0");
            }
        }
        return strBuffer.toString();
    }

    /**
     * 获取字符数量 汉字占2个长度，英文占1个长度
     *
     * @param str
     * @return
     */
    public static int getTextLength(String str) {
        int length = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) > 255) {
                length += 2;
            } else {
                length++;
            }
        }
        return length;
    }



    /**
     * 将kb转为mb/gb/tb
     *
     * @param b
     * @return
     */
    public static String KBToMBGBTB(double b) {
        BigDecimal bigDecimal = new BigDecimal(Double.toString(b));
        BigDecimal bigDecimalBasic = new BigDecimal(1024);
        if (b < 1024) {
            return formatDouble1(b) + "MB";
        } else {
            int gb = (int) b / 1024;
            if (gb < 1024) {
                return (bigDecimal.divide(bigDecimalBasic, 2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "GB";
            } else {
                BigDecimal bigDecimal1 = new BigDecimal(1024 * 1024);
                return (bigDecimal.divide(bigDecimal1, 2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "TB";
            }
        }
    }

    /**
     * HTML转纯文本
     *
     * @param htmlString
     * @return
     */
    public static String htmlToString(String htmlString) {
        String regFormat = "\\s*|\t|\r|\n";
        String regTag = "<[^>]*>";
        return htmlString.replaceAll(regFormat, "").replaceAll(regTag, "");

    }
    public static String encode(byte[] bytes) {
        if (null == bytes || 0 == bytes.length) {
            return null;
        }
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(bytes);

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getDegreeString(double radian) {
        int degree = 0;
        double minute = 0;
        double second = 0;
        try {
            double d = Math.toDegrees(radian);
            degree = (int)d;
            minute = (d - degree) * 60;
            second = (minute - (int)minute) * 60;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.format("%1$s ° %2$s ′ %3$.4f ″", degree,(int)minute,second);
    }
    /**
     * 度分秒转经纬度
     * @param dms 116°25'7.85"
     * @return 116.418847
     */
    public static double changeToDu(String dms) {
        if (dms == null) return 0;
        try {
            dms = dms.replace(" ", "");
            String[] str2 = dms.split("°");
            if (str2.length < 2) return 0;
            int d = Integer.parseInt(str2[0]);
            String[] str3 = str2[1].split("'");
            if (str3.length < 2) return 0;
            int f = Integer.parseInt(str3[0]);
            String str4 = str3[1].substring(0, str3[1].length() - 1);
            double m = Double.parseDouble(str4);

            double fen = f + (m / 60);
            double du = (fen / 60) + Math.abs(d);
            if (d < 0) du = -du;
            return du;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String changeToStr(String dms) {

        return reservedLocStr(changeToDu(dms),6);
    }

    /**
     * 将经纬度转换为度分秒格式
     * @param du 116.418847
     * @return 116°25'7.85"
     */
    public static String changeToDFM(double du) {
        int du1 = (int) du;
        double tp = (du - du1) * 60;
        int fen = (int) tp;

        String miao = String.format("%.2f", Math.abs(((tp - fen) * 60)));
        return du1 + "°" + Math.abs(fen) + "'" + miao + "\"";
    }
    /**
     * 保留几位小数点
     */
    public static double reservedLoc(double du,int index) {
        return   BigDecimal.valueOf(du).setScale(index,BigDecimal.ROUND_HALF_UP).doubleValue();
    }


    /**
     * 保留几位小数点
     */
    public static String reservedLocStr(double du,int index) {
        return   BigDecimal.valueOf(du).setScale(index,BigDecimal.ROUND_HALF_UP).toString();
    }
    /**
     * 功能：  度-->度分秒（满足图片格式）
     * @param d   传入待转化格式的经度或者纬度
     * @return
     */
    public  static String DDtoDMS_photo(Double d){
        try {
            //double dd = Convert.ToDouble(str);
            String str = "" + d;
            int p = str.indexOf(".");
            int dt = Integer.parseInt(str.substring(0, p));
            d = d - dt;
            double M = d * 60;
            int mt = (int) M;
            M = (M - mt) * 60;
            if (Math.abs(M - 60) < 0.001) {
                M = 0;
                mt = mt + 1;
            }
            if (mt == 60) {
                dt = dt + 1;
                mt = 0;
            }
            return ""+dt+"°"+mt+"′"+(int)M+"″";
        } catch(Exception e)  {
            return  "0";
        }
    }

}
